package com.five.service.impl;

import com.five.common.DataGridView;
import com.five.common.UUIDUtil;
import com.five.common.UserUtil;
import com.five.common.exception.MyException;
import com.five.config.security.User;
import com.five.domain.SysPermission;
import com.five.domain.SysRole;
import com.five.domain.SysUser;
import com.five.mapper.PermissionMapper;
import com.five.mapper.RoleMapper;
import com.five.mapper.UserMapper;
import com.five.service.UserService;
import com.five.vo.UserVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionMapper permissionMapper;

    //重写登录验证方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("该用户不存在！");
        }
        List<SysPermission> powerList = permissionMapper.queryPermissionByUserId(1,user.getId(),null);
        user.setPermissions(powerList);
        user.setRoles(roleMapper.queryRoleByUid(1,user.getId()));
        return user;
    }

    //加载用户列表
    @Override
    public DataGridView queryAllUser(UserVo userVo) {
        Page<Object> page = PageHelper.startPage(userVo.getPage(), userVo.getLimit());
        List<SysUser> data = userMapper.queryAllUser(userVo);
        return new DataGridView(page.getTotal(), data);
    }

    //添加员工
    @Override
    @Transactional
    public void addStaff(UserVo userVo) throws MyException {
        SysUser user = new SysUser();
        user.setUsername(userVo.getUsername());
        SysUser sysUser = userMapper.queryUserByAll(user);
        if(sysUser!=null) throw new MyException("用户名重复");
        userVo.setId(UUIDUtil.getUUID());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        userVo.setType(1);
        userVo.setPassword(encoder.encode("123456"));
        userMapper.addUser(userVo);
        userMapper.addUserRole(userVo.getId(),4);
    }

    //修改员工
    @Override
    @Transactional
    public void updateStaff(UserVo userVo) {
        userMapper.updateUser(userVo);
    }

    //禁用顾客
    @Override
    @Transactional
    public void banCustomer(String id, Integer available) {
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        if (available==0) sysUser.setAvailable(1);
        if (available==1) sysUser.setAvailable(0);
        userMapper.updateUser(sysUser);
    }

    //加载用户管理的分配角色的数据
    @Override
    public DataGridView queryStaffRole(String id) {
        //1,查询所有可用的角色
        SysRole role=new SysRole();
        role.setAvailable(1);
        List<SysRole> allRole= roleMapper.queryAllRole(role);
        //2,根据用户ID查询已拥有的角色
        List<SysRole> userRole=roleMapper.queryRoleByUid(1,id);

        List<Map<String,Object>> data=new ArrayList<>();
        for (SysRole r1 : allRole) {
            Boolean LAY_CHECKED=false;
            for (SysRole r2 : userRole) {
                if(r1.getId()==r2.getId()) {
                    LAY_CHECKED=true;
                }
            }
            Map<String, Object> map=new HashMap<>();

            map.put("id", r1.getId());
            map.put("name", r1.getName());
            map.put("nameZh", r1.getNameZh());
            map.put("remark", r1.getRemark());
            map.put("LAY_CHECKED", LAY_CHECKED);
            data.add(map);
        }
        return new DataGridView(data);
    }
    //保存用户和角色的关系
    @Override
    @Transactional
    public void saveStaffRole(UserVo userVo) {
        String uid = userVo.getId();
        Integer[] roleIds = userVo.getIds();
        //根据用户id删除sys_role_user里面的数据
        roleMapper.deleteRoleUserByUid(uid);
        //保存关系
        if(roleIds!=null&& roleIds.length>0) {
            for (Integer rid : roleIds) {
                userMapper.addUserRole(uid,rid);
            }
        }
    }

    //重置密码
    @Override
    @Transactional
    public void resetPwd(String id) {
        SysUser sysUser = new SysUser();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        sysUser.setPassword(encoder.encode("123456"));
        sysUser.setId(id);
        userMapper.updateUser(sysUser);
    }

    //修改密码
    @Override
    @Transactional
    public void updatePwd(String oldpassword, String newpassword) throws MyException {
        User user = UserUtil.getUser();
        SysUser sysUser = new SysUser();
        sysUser.setId(user.getId());
        SysUser sysUser1 = userMapper.queryUserByAll(sysUser);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(oldpassword,sysUser1.getPassword())) throw new MyException("旧密码错误");
        sysUser.setPassword(encoder.encode(newpassword));
        userMapper.updateUser(sysUser);
    }

    //查询个人资料
    @Override
    public DataGridView queryUser() {
        User user = UserUtil.getUser();
        SysUser sysUser = new SysUser();
        sysUser.setId(user.getId());
        SysUser sysUser1 = userMapper.queryUserByAll(sysUser);
        sysUser1.setPassword("");
        return new DataGridView(sysUser1);
    }

    //统计用户总数
    @Override
    public DataGridView countUser(SysUser sysUser) {
        Long count = userMapper.countUser(sysUser.getAvailable(),sysUser.getType());
        return new DataGridView(count,"");
    }

    //注册功能
    @Override
    @Transactional
    public void addCustomer(UserVo userVo) throws MyException {
        SysUser user = new SysUser();
        user.setUsername(userVo.getUsername());
        SysUser sysUser = userMapper.queryUserByAll(user);
        if(sysUser!=null) throw new MyException("用户名重复");
        userVo.setId(UUIDUtil.getUUID());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        userVo.setType(0);
        userVo.setPassword(encoder.encode(userVo.getPassword()));
        userMapper.addUser(userVo);
    }

    //修改个人信息
    @Override
    @Transactional
    public void updateInfo(UserVo userVo) {
        userVo.setId(UserUtil.getUser().getId());
        userMapper.updateUser(userVo);
    }

    //导航栏可用员工
    @Override
    public List<SysUser> queryStaffByUse() {
        return userMapper.queryStaffByUse();
    }
}
